package com.tianyu.inspection.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tianyu.inspection.common.enums.DangerStatus;
import com.tianyu.inspection.common.model.PageModel;
import com.tianyu.inspection.service.api.IDangerProcessService;
import com.tianyu.inspection.service.websocket.WebSocketService;
import com.tianyu.inspection.common.component.AppConstants;
import com.tianyu.inspection.entity.Danger;
import com.tianyu.inspection.entity.DangerProcess;
import com.tianyu.inspection.entity.User;
import com.tianyu.inspection.entity.model.OperateMo;
import com.tianyu.inspection.entity.model.QueryMo;
import com.tianyu.inspection.mapper.DangerMapper;
import com.tianyu.inspection.mapper.DangerProcessMapper;
import com.tianyu.inspection.mapper.UserMapper;
import io.ocs.model.OcsSimpleModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**********************************
 * @Author YSW
 * @Description 险情处理服务
 * @Date 2021/1/12 - 15:39
 **********************************/

@Service
public class DangerProcessServiceImpl implements IDangerProcessService {

    @Resource
    private WebSocketService webSocketService;

    @Resource
    private DangerMapper dangerMapper;

    @Resource
    private DangerProcessMapper dangerProcessMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private AppConstants appConstants;
    
    @Resource
    private OcsSimpleModel ocsSimpleModel;

    /**
     * 分页查询
     *
     * @param queryMo 参数模型
     * @return ModelMap
     */
    @Override
    public IPage<DangerProcess> searchListPage(QueryMo queryMo) {
        IPage<DangerProcess> page = PageModel.getModelPage(queryMo, dangerProcessMapper);
        if (Objects.nonNull(queryMo.get("roleId")) && queryMo.get("roleId").equals(4)){
            return page;
        }
        Set<Integer> ids = new HashSet<>();
        page.getRecords().forEach(dangerProcess -> {
            ids.add(dangerProcess.getInspectorId());
        });
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (ids.size()>0){
            wrapper.in("id",ids);
        }
        if (Objects.nonNull(queryMo.get("projectId"))){
            wrapper.eq("project_id",queryMo.get("projectId"));
        }
        List<User> userList = userMapper.selectList(wrapper);
        Map<Integer,User> userMap = new HashMap<>(10);
        userList.forEach(user -> {
            userMap.put(user.getId(),user);
        });
        page.getRecords().forEach(dangerProcess -> {
            User user = userMap.get(dangerProcess.getInspectorId());
            dangerProcess.setInspectorName(user.getNickName());
            dangerProcess.setInspectorPhone(user.getPhone());
            if (Objects.nonNull(dangerProcess.getSceneImage())){
                dangerProcess.setSceneImage(ocsSimpleModel.getObjectUrl(dangerProcess.getSceneImage()));
            }
        });
        return page;
    }

    /**
     * 查询单个险情的对应处理进程
     *
     * @param queryMo 查询参数
     * @return IPage<ModelMap>
     */
    @Override
    public List<DangerProcess> selectDangerProcessAndInspectorList(QueryMo queryMo) {
        List<DangerProcess> list = dangerProcessMapper.selectDangerProcessAndInspectorList(queryMo);
        list.forEach(dangerProcess -> {
            if (Objects.nonNull(dangerProcess.getSceneImage())){
                dangerProcess.setSceneImage(ocsSimpleModel.getObjectUrl(dangerProcess.getSceneImage()));
            }
        });
        return list;
    }


    /**
     * 通过ID等参数查询一条数据
     *
     * @param queryMo 参数集[实体ID 与 项目ID, 数据状态等]
     * @return 单条记录结果
     */
    @Override
    public DangerProcess selectOne(QueryMo queryMo) {
        if(Objects.nonNull(queryMo.getEqMap().get("id"))){
            DangerProcess dangerProcess = dangerProcessMapper.selectOne(new QueryWrapper<DangerProcess>().allEq(queryMo.getEqMap()));
            if (Objects.nonNull(dangerProcess) && Objects.nonNull(dangerProcess.getSceneImage())){
                dangerProcess.setSceneImage(ocsSimpleModel.getObjectUrl(dangerProcess.getSceneImage()));
            }
            return dangerProcess;
        }
        return null;
    }

    /**
     * 插入一条数据
     *
     * @param operateMo 实体对象
     * @return 是否操作成功
     */
    @Override
    public boolean insert(OperateMo operateMo) {
        ObjectMapper objectMapper = new ObjectMapper();
        DangerProcess dangerProcess = objectMapper.convertValue(operateMo.getEntity(), DangerProcess.class);
        return 1 == dangerProcessMapper.insert(dangerProcess);
    }

    /**
     * 通过ID删除一条数据
     *
     * @param queryMo 参数集[实体ID 与 项目ID, 数据状态等]
     * @return 是否操作成功
     */
    @Override
    public boolean delete(QueryMo queryMo) {
        if(Objects.nonNull(queryMo.getEqMap().get("id"))){
            return 1 == dangerProcessMapper.delete(new QueryWrapper<DangerProcess>().allEq(queryMo.getEqMap()));
        }
        return false;
    }

    /**
     * 更新一条数据
     *
     * @param operateMo 更新参数集
     * @return ModelMap
     */
    @Override
    public boolean update(OperateMo operateMo) {
        ObjectMapper objectMapper = new ObjectMapper();
        DangerProcess dangerProcess = objectMapper.convertValue(operateMo.getEntity(), DangerProcess.class);
        dangerProcess.setDealTime(new Date());
        dangerProcess.setRemarks(null);
        dangerProcess.setDangerId(null);
        dangerProcess.setStatus(DangerStatus.DANGER_STATUS_FINISH.getValue());
        boolean result = 1 == dangerProcessMapper.update(dangerProcess, new QueryWrapper<DangerProcess>().allEq(operateMo.getEqMap()));
        if(result){
            DangerProcess dangerProcess1 = dangerProcessMapper.selectById((Integer) operateMo.get("id"));
            dangerMapper.update(new Danger().setStatus(DangerStatus.DANGER_STATUS_FINISH.getValue()),
                    new QueryWrapper<Danger>().eq("id",dangerProcess1.getDangerId()));
            webSocketService.sendPatrolDealMessage((Integer) operateMo.getEqMap().get("project_id"),dangerProcess1.getDangerId());
        }
        return result;
    }

    /**
     * 通过ID逻辑删除一条数据
     *
     * @param queryMo 参数集[实体ID 与 项目ID, 数据状态等]
     * @return 是否操作成功
     */
    @Override
    public boolean logicallyDelete(QueryMo queryMo) {
        return 1 == dangerProcessMapper.update(
                new DangerProcess().setState(1),
                new QueryWrapper<DangerProcess>().allEq(queryMo.getEqMap())
        );
    }
}
